<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="rules"
    label-width="120px"
    class="notice-form"
  >
    <el-form-item label="公告发布时间" prop="publishDate">
      <el-date-picker
        v-model="formData.publishDate"
        type="datetime"
        placeholder="选择日期时间"
        format="YYYY-MM-DD HH:mm:ss"
        value-format="YYYY-MM-DD HH:mm:ss"
        style="width: 100%"
      />
    </el-form-item>

    <el-form-item label="公告发布内容" prop="content">
      <el-input
        v-model="formData.content"
        type="textarea"
        :rows="6"
        placeholder="请输入公告内容"
      />
    </el-form-item>
  </el-form>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { publishNotice } from '../../apis/notice'

const formRef = ref(null)

// 格式化当前时间为字符串
const formatDateTime = (date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hour = String(date.getHours()).padStart(2, '0')
  const minute = String(date.getMinutes()).padStart(2, '0')
  const second = String(date.getSeconds()).padStart(2, '0')

  return `${year}-${month}-${day} ${hour}:${minute}:${second}`
}

// 生成表单数据
const formData = reactive({
  publishDate: formatDateTime(new Date()),
  content: '',
})

// 更新当前时间
onMounted(() => {
  formData.publishDate = formatDateTime(new Date())
})

// 表单验证规则
const rules = reactive({
  publishDate: [
    { required: true, message: '请选择发布时间', trigger: 'change' },
  ],
  content: [
    { required: true, message: '请输入公告内容', trigger: 'blur' },
    {
      min: 2,
      max: 2000,
      message: '内容长度应在2到2000个字符之间',
      trigger: 'blur',
    },
  ],
})

// 处理表单提交
const submitForm = async () => {
  if (!formRef.value) return null

  try {
    const valid = await formRef.value.validate()
    if (!valid) return null

    // 准备要提交的数据
    const noticeData = {
      publishTime: formData.publishDate,
      content: formData.content,
    }

    // 调用API发送数据到后端
    await publishNotice(noticeData)

    ElMessage.success('公告发布成功')
    resetForm()

    return noticeData
  } catch (error) {
    ElMessage.error('公告发布失败: ' + (error.message || '未知错误'))
    console.error(error)
    return null
  }
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
    formData.publishDate = formatDateTime(new Date()) // 重置为当前时间
  }
}

// 暴露方法给父组件
defineExpose({
  submitForm,
  resetForm,
})
</script>

<style lang="scss" scoped>
.notice-form {
  padding: 20px 0;
  width: 100%;

  .el-input,
  .el-textarea,
  .el-date-picker {
    width: 100%;
  }
}
</style>
